package com.buss.core.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.buss.core.sysparam.SysStaticParam;
import com.buss.core.validator.ResultMessage;

public class WebExceptionResolver extends SimpleMappingExceptionResolver {

	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ex.printStackTrace();
		String viewName = determineViewName(ex, request);
		Map<String, Object> map = new HashMap<String, Object>();
		ResultMessage resultMessage = (ResultMessage) request
				.getAttribute(SysStaticParam.RESULT_MESSAGE);
		String code = "-1";
		String message = "";

		if (ex instanceof LoginException) {
			code = "-2";
			message = "没有登录系统或session已经失效，请重新登录!";
		} else if (ex instanceof PermissionException) {
			code = "100";
			message = "没有权限操作该功能，请与系统管理员联系!";
		} else {
			code = "-1";
			message = "操作失败，原因:" + ex.getMessage();
		}
		if (resultMessage == null) {
			resultMessage = new ResultMessage(code, message);
		}
		map.put("message", resultMessage);
		if (viewName != null) {
			if (!(request.getHeader("accept").toLowerCase()
					.indexOf("application/json") > -1)
					|| !(request.getHeader("X-Requested-With").toLowerCase()
							.indexOf("xmlhttprequest") > -1)) {
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}

				return getModelAndView(viewName, ex, request).addObject(
						SysStaticParam._MESSAGE, resultMessage);
			} else {
				try {
					ObjectMapper mapper = new ObjectMapper();
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					JsonGenerator jsonGenerator = mapper.getJsonFactory()
							.createJsonGenerator(response.getOutputStream(),
									JsonEncoding.UTF8);
					jsonGenerator.writeObject(map);
					response.getOutputStream().flush();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						response.getOutputStream().close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				return new ModelAndView();
			}
		}
		return null;
	}

	public static void main(String[] args) throws Exception{
//		ObjectMapper mapper = new ObjectMapper();
//		String s = "{ \"name\" : {\"tt\":\"萧远山\", \"sex\" : \"男\", \"age\" : \"23\",\"address\" : \"河南郑州\"}}";
//		try {
//			Map<?, ?> map = mapper.readValue(s, Map.class);
//			System.out.println(map.size());
//			Iterator<?> iterator = map.keySet().iterator();
//			while (iterator.hasNext()) {
//				Object key = iterator.next();
//				System.out.print(key + ":");
//				System.out.println(map.get(key).toString());
//			}
//		} catch (JsonParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (JsonMappingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", null);
		
		JsonGenerator jsonGenerator = mapper.getJsonFactory()
				.createJsonGenerator(System.out,
						JsonEncoding.UTF8);
		jsonGenerator.writeObject(map);
	}
}
